/*
 * Copyright 2007 The semap project development team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Created by ru0bdu at 29 Nov 2007 10:18:18.
 *
 * $Id: NTriplesUtil.java 857 2007-11-29 09:44:13Z dulanov $
 */

package net.sf.semap.sandbox.rio.ntriples;

import org.openrdf.model.BNode;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;

/**
 * @author <a href="mailto:dulanov@gmail.com">dulanov</a>
 * @see org.openrdf.rio.ntriples.NTriplesUtil
 * @version $Id: NTriplesUtil.java 857 2007-11-29 09:44:13Z dulanov $
 */
public class NTriplesUtil {

	/**
	 * Creates an N-Triples string for the supplied value.
	 */
	public static String toNTriplesString(Value value) {
		if (value instanceof Resource) {
			return toNTriplesString((Resource) value);
		} else if (value instanceof Literal) {
			return toNTriplesString((Literal) value);
		} else {
			throw new IllegalArgumentException("Unknown value type: " + value.getClass());
		}
	}

	/**
	 * Creates an N-Triples string for the supplied resource.
	 */
	public static String toNTriplesString(Resource resource) {
		if (resource instanceof URI) {
			return toNTriplesString((URI) resource);
		} else if (resource instanceof BNode) {
			return toNTriplesString((BNode) resource);
		} else {
			throw new IllegalArgumentException("Unknown resource type: " + resource.getClass());
		}
	}

	/**
	 * Creates an N-Triples string for the supplied URI.
	 */
	public static String toNTriplesString(URI uri) {
		return "<" + uri.toString() + ">";
	}

	/**
	 * Creates an N-Triples string for the supplied bNode.
	 */
	public static String toNTriplesString(BNode bNode) {
		return "_:" + bNode.getID();
	}

	/**
	 * Creates an N-Triples string for the supplied literal.
	 */
	public static String toNTriplesString(Literal lit) {
		// Do some character escaping on the label:
		StringBuilder sb = new StringBuilder(128);
		sb.append("\"");
		sb.append(lit.getLabel());
		sb.append("\"");

		if (lit.getDatatype() != null) {
			// Append the literal's datatype
			sb.append("^^");
			sb.append(toNTriplesString(lit.getDatatype()));
		} else if (lit.getLanguage() != null) {
			// Append the literal's language
			sb.append("@");
			sb.append(lit.getLanguage());
		}

		return sb.toString();
	}
}